#include <memory>
#include <iostream>
#include <brpc/server.h>
#include <butil/logging.h>

// common文件夹下
#include "asrer.hpp"
#include "etcder.hpp"
#include "logger.hpp"
#include "filer.hpp"
#include "uuid.hpp"
#include "base.pb.h"
#include "file.pb.h"

namespace bite_im
{
    // 文件服务接口类
    class FileServiceImpl : public FileService
    {

    public:
        using ptr = std::shared_ptr<FileServiceImpl>;
        FileServiceImpl(const std::string &storage_path) : _storage_path(storage_path)
        {
            umask(0);
            mkdir(storage_path.c_str(), 0775);
            if (_storage_path.back() != '/')
            {
                _storage_path.push_back('/');
            }
        }
        ~FileServiceImpl() {}
        // 获取单个文件
        void GetSingleFile(google::protobuf::RpcController *controller,
                           const ::bite_im::GetSingleFileReq *request,
                           ::bite_im::GetSingleFileRsp *response,
                           ::google::protobuf::Closure *done)
        {
            // 管理rpc对象
            brpc::ClosureGuard rpc_guard(done);
            // 获取文件id--即文件名
            std::string fid = request->file_id();
            std::string file_name = _storage_path + fid;
            // 读取文件数据
            std::string body;
            bool ret = Filer::readFile(file_name, body);
            if (ret == false)
            {
                response->set_request_id(request->request_id());
                response->set_success(false);
                response->set_errmsg("读取文件[" + file_name + "]失败");
                LOG_ERROR("读取文件失败，请求id[{}]", request->request_id());
                return;
            }
            response->set_request_id(request->request_id());
            response->set_success(true);
            // 将文件内容写入file_data结构体中
            response->mutable_file_data()->set_file_id(fid);
            response->mutable_file_data()->set_file_content(body);
        }
        // 获取多个文件
        void GetMultiFile(google::protobuf::RpcController *controller,
                          const ::bite_im::GetMultiFileReq *request,
                          ::bite_im::GetMultiFileRsp *response,
                          ::google::protobuf::Closure *done)
        {
            // 管理rpc对象
            brpc::ClosureGuard rpc_guard(done);
            for (int i = 0; i < request->file_id_list_size(); i++)
            {
                std::string fid = request->file_id_list(i);
                std::string file_name = _storage_path + fid;
                std::string body;
                bool ret = Filer::readFile(file_name, body);
                if (ret == false)
                {
                    response->set_request_id(request->request_id());
                    response->set_success(false);
                    response->set_errmsg("读取文件[" + file_name + "]失败");
                    LOG_ERROR("读取文件失败，请求id[{}]", request->request_id());
                    return;
                }
                // response->mutable_file_data()获取到一个Map<string, FileDownloadData> 实现fid和文件有关数据的映射
                FileDownloadData data;
                data.set_file_id(fid);
                data.set_file_content(body);
                response->mutable_file_data()->insert({fid, data});
            }
            response->set_request_id(request->request_id());
            response->set_success(true);
        }
        // 上传单个文件
        void PutSingleFile(google::protobuf::RpcController *controller,
                           const ::bite_im::PutSingleFileReq *request,
                           ::bite_im::PutSingleFileRsp *response,
                           ::google::protobuf::Closure *done)
        {
            // 管理rpc对象
            brpc::ClosureGuard rpc_guard(done);
            std::string fid = UUID::uuid();
            std::string file_name = _storage_path + fid;
            bool ret = Filer::writeFile(file_name, request->file_data().file_content());
            if (ret == false)
            {
                response->set_request_id(request->request_id());
                response->set_success(false);
                response->set_errmsg("写入文件失败");
                LOG_ERROR("写入文件失败，请求id[{}]", request->request_id());
                return;
            }
            response->set_request_id(request->request_id());
            response->set_success(true);
            response->mutable_file_info()->set_file_id(fid);
            response->mutable_file_info()->set_file_size(request->file_data().file_size());
            response->mutable_file_info()->set_file_name(request->file_data().file_name());
        }
        // 上传多个文件
        void PutMultiFile(google::protobuf::RpcController *controller,
                          const ::bite_im::PutMultiFileReq *request,
                          ::bite_im::PutMultiFileRsp *response,
                          ::google::protobuf::Closure *done)
        {
            // 管理rpc对象
            brpc::ClosureGuard rpc_guard(done);
            for (int i = 0; i < request->file_data_size(); i++)
            {
                std::string fid = UUID::uuid();
                std::string file_name = _storage_path + fid;
                bool ret = Filer::writeFile(file_name, request->file_data(i).file_content());
                if (ret == false)
                {
                    response->set_request_id(request->request_id());
                    response->set_success(false);
                    response->set_errmsg("写入文件失败");
                    LOG_ERROR("写入文件失败，请求id[{}]", request->request_id());
                    return;
                }
                FileMessageInfo *info = response->add_file_info();
                info->set_file_id(fid);
                info->set_file_size(request->file_data(i).file_size());
                info->set_file_name(request->file_data(i).file_name());
            }
            response->set_request_id(request->request_id());
            response->set_success(true);
        }

    private:
        std::string _storage_path;
    };
    // 文件RPC服务器对象
    class FileServer
    {
        using RpcServerPtr = std::shared_ptr<brpc::Server>;

    public:
        using ptr = std::shared_ptr<FileServer>;
        FileServer(const Registry::ptr &reg_server, const RpcServerPtr &rpc_server)
            : _reg_server(reg_server), _rpc_server(rpc_server) {}
        ~FileServer() {}

        // 启动RPC服务器
        void start()
        {
            _rpc_server->RunUntilAskedToQuit();
        }

    private:
        Registry::ptr _reg_server;
        RpcServerPtr _rpc_server;
    };
    /*建造者设计模式，封装对象的构造过程，防止用户在进行操作时，对未构造的对象进行操作*/

    class FileServerBuilder
    {
        using RpcServerPtr = std::shared_ptr<brpc::Server>;

    public:
        // 构造服务注册客户端对象
        void make_reg_object(const std::string &reg_host,
                             const std::string &service_name,
                             const std::string &access_host)
        {
            _reg_client = std::make_shared<Registry>(reg_host);
            _reg_client->registry(service_name, access_host);
        }
        // 搭建rpc服务器
        void make_rpc_server(uint16_t port, int32_t time_out, uint8_t num_threads, const std::string &storage_path = "./data/")
        {
            // 创建rpc服务器对象
            _rpc_server = std::make_shared<brpc::Server>();
            // 构建服务，并添加服务
            FileServiceImpl *file_service = new FileServiceImpl(storage_path); // 注意这里需要在堆上开辟空间  -----还没有传参
            int ret = _rpc_server->AddService(file_service, brpc::ServiceOwnership::SERVER_OWNS_SERVICE);
            if (ret == -1)
            {
                LOG_ERROR("rpc服务器添加服务失败");
                abort();
            }

            auto options = std::make_shared<brpc::ServerOptions>();
            // 启动服务器
            options->idle_timeout_sec = time_out; // 连接空闲超时时间
            options->num_threads = num_threads;
            ret = _rpc_server->Start(port, options.get());
            if (ret == -1)
            {
                LOG_ERROR("服务器启动失败");
                abort();
            }
        }
        FileServer::ptr build()
        {
            if (_reg_client.get() == nullptr)
            {
                LOG_ERROR("服务器建造失败，未初始化服务注册模块");
                abort();
            }
            if (_rpc_server.get() == nullptr)
            {
                LOG_ERROR("服务器建造失败，未搭建Rpc服务器");
                abort();
            }
            FileServer::ptr server = std::make_shared<FileServer>(_reg_client, _rpc_server); // -----还没有传参
            return server;
        }

    private:
        Registry::ptr _reg_client;
        RpcServerPtr _rpc_server;
    };

};
